package com.koron.order.linepatrol.uav.excel;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.util.ListUtils;
import com.koron.bean.base.Response;
import com.koron.order.linepatrol.satellite.excel.LineAnalysisEventListener;
import com.koron.order.linepatrol.uav.bean.VO.LineRiskPatrolUnvDetail;
import com.koron.order.linepatrol.uav.bean.excel.LineRiskPatrolUnvDetailExcel;
import com.koron.order.linepatrol.uav.converter.LineRiskPatrolUnvConverter;
import com.koron.order.linepatrol.uav.service.LineRiskPatrolUnvDetailService;
import com.koron.order.overhaul.bean.dto.Equipment;
import com.koron.order.risk.feign.LineEquipmentFeign;
import com.koron.order.risk.feign.dto.EquipmentParams;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.ADOConnection;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName: LineRiskPatrolUnvDetailListener
 * @Description:
 * @Date: 2023/2/11
 * @Author: 李一辰
 * @Version: 1.0
 **/
@Slf4j
@AllArgsConstructor
public class LineRiskPatrolUnvDetailListener extends LineAnalysisEventListener<LineRiskPatrolUnvDetailExcel> {
    private final LineRiskPatrolUnvDetailService lineRiskPatrolUnvDetailService;

    private final LineRiskPatrolUnvConverter lineRiskPatrolUnvConverter;
    private final LineEquipmentFeign equipmentFeign;

    private final String monitorId;
    // 每隔100条，然后清理list ，方便内存回收
    private static final int BATCH_COUNT = 100;
    // 要保存的数据
    private final List<LineRiskPatrolUnvDetail> linePatrolSatelliteList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);


    @Override
    public void invoke(LineRiskPatrolUnvDetailExcel data, AnalysisContext context) {
        LineRiskPatrolUnvDetail lineRiskPatrolUnvDetail = fillData(data);
        if (lineRiskPatrolUnvDetail == null) {
            return;
        }
        linePatrolSatelliteList.add(lineRiskPatrolUnvDetail);
        if (linePatrolSatelliteList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            linePatrolSatelliteList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    private void saveData() {
        computeManageDept();
        ADOConnection.runTask(getCurrDs(), lineRiskPatrolUnvDetailService, "saveBatch", Boolean.class, linePatrolSatelliteList);
        log.info("存储数据库成功！");
    }

    private void computeManageDept() {
        List<String> ids = linePatrolSatelliteList.stream().map(LineRiskPatrolUnvDetail::getTowerId).collect(Collectors.toList());

        Response<List<EquipmentParams>> batchBaseParams = equipmentFeign.getBatchBaseParams(ids);
        if (CollUtil.isEmpty(batchBaseParams.getData())) {
            return;
        }

        List<EquipmentParams> data = batchBaseParams.getData();
        Map<String, EquipmentParams> deptMap = data.stream()
                .filter(e -> "管理部门".equals(e.getParamName()))
                .collect(Collectors.toMap(EquipmentParams::getEquipmentId, e -> e, (o1, o2) -> o1));
        for (LineRiskPatrolUnvDetail lineRiskPatrolUnvDetail : linePatrolSatelliteList) {
            EquipmentParams params = deptMap.get(lineRiskPatrolUnvDetail.getTowerId());
            lineRiskPatrolUnvDetail.setBelongDeptId(params.getParamResult());
            lineRiskPatrolUnvDetail.setBelongDeptName(params.getParamValue());
        }

    }

    private LineRiskPatrolUnvDetail fillData(LineRiskPatrolUnvDetailExcel data) {
        if (data == null) {
            return null;
        }
        LineRiskPatrolUnvDetail lineRiskPatrolUnvDetail = lineRiskPatrolUnvConverter.excelToEntity(data);
        lineRiskPatrolUnvDetail.setMonitorId(monitorId);
        lineRiskPatrolUnvDetail.setRiskParentType("高压线路");
        // 导入巡视记录时，初始核实状态为待核实
        lineRiskPatrolUnvDetail.setCheckStatus("1");
        String lineName = lineRiskPatrolUnvDetail.getEquipmentName();
        if (lineName == null) {
            fillError(data, 0, "线路名称不能为空");
        }
        Equipment line = getLineByName(lineRiskPatrolUnvDetail.getEquipmentName());
        if (line == null) {
            fillError(data, 0, "线路：" + lineRiskPatrolUnvDetail.getEquipmentName() + "不存在");
            return null;
        } else {
            lineRiskPatrolUnvDetail.setEquipmentId(line.getId());
        }

        // 杆塔
        if (StrUtil.isEmpty(lineRiskPatrolUnvDetail.getTowerName())) {
            fillError(data, 1, "杆塔不能为空");
            return null;
        }
        Equipment tower = getTowerByNameAndChildren(line.getName(), lineRiskPatrolUnvDetail.getTowerName(), line.getChildren());
        if (tower == null) {
            fillError(data, 1, "杆塔：" + data.getTowerName() + "不存在");
            return null;
        } else {
            lineRiskPatrolUnvDetail.setTowerId(tower.getId());
        }
        //风险子类和风险关键字校验
        if (lineRiskPatrolUnvDetail.getRiskType() == null) {
            fillError(data, 2, "风险子类不能为空");
            return null;
        }

        if (lineRiskPatrolUnvDetail.getRiskKeyword() == null) {
            fillError(data, 3, "风险关键字不能为空");
            return null;
        }
        if (lineRiskPatrolUnvDetail.getRiskLevel() == null) {
            fillError(data, 4, "风险等级不能为空");
            return null;
        }
        return lineRiskPatrolUnvDetail;

    }


}
